import { serverUrl } from './../defines'

export default function(){
  let that = {};
  let _socket = undefined;
  let _callBackMap = {};
  let _callBackIndex = 1;
  that.init = function(){
    _socket = io(serverUrl);
    _socket.on('notify', data => {
      console.log(`notify = ${JSON.stringify(data)}`);
      let callBackIndex = data.callBackIndex;
      let cb = _callBackMap[callBackIndex];
      if (cb) {
        cb(null, data.data);
      }
    })
  };

  const notify = (msg, data) => {
    _socket.emit('notify', {callBackIndex: _callBackIndex, data, msg });
    _callBackIndex ++;
  };

  const request = (msg, data, cb) => {
    _callBackMap[_callBackIndex] = cb;
    notify(msg, data);
  };

  that.login = (unique, nickname, avatar, cb)=> {
    // _socket.emit('login', {
    //     uniqueID: unique,
    //     nickName: nickname,
    //     avatarUrl: avatar
    // });
    request('login', { uniqueId: unique, nickName: nickname, avatarUrl: avatar });
  };
  // that.onLogin = res => {
  //   _socket.on('login', data => {
  //     console.log(`login = ${JSON.stringify(data) }`);
  //   });
  // };
  return that;
};